<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Universal Debug Logger Test</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
        background-color: #f5f5f5;
      }

      .container {
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      }

      h1 {
        color: #333;
        text-align: center;
      }

      .button-group {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 10px;
        margin: 20px 0;
      }

      button {
        padding: 12px 16px;
        border: none;
        border-radius: 6px;
        background: #007acc;
        color: white;
        cursor: pointer;
        font-size: 14px;
        transition: background 0.2s;
      }

      button:hover {
        background: #005a99;
      }

      .status {
        background: #e8f5e8;
        border: 1px solid #4caf50;
        padding: 10px;
        border-radius: 4px;
        margin: 20px 0;
      }

      .info {
        background: #f0f8ff;
        border: 1px solid #007acc;
        padding: 15px;
        border-radius: 4px;
        margin: 20px 0;
      }

      .code {
        background: #f4f4f4;
        border: 1px solid #ddd;
        padding: 10px;
        border-radius: 4px;
        font-family: monospace;
        font-size: 12px;
        overflow-x: auto;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h1>🐛 Universal Debug Logger 测试页面</h1>

      <div class="info">
        <h3>📋 使用说明:</h3>
        <p>1. 确保服务器运行在端口3000</p>
        <p>2. 打开调试面板: <a href="/debug-panel.html" target="_blank">Debug Panel</a></p>
        <p>3. 点击下面的按钮测试各种功能</p>
        <p>4. 在调试面板中查看日志和网络请求</p>
      </div>

      <div class="status" id="status">连接状态: <span id="connection-status">检测中...</span></div>

      <div class="button-group">
        <button onclick="testBasicLogging()">基础日志测试</button>
        <button onclick="testDevToolsAPI()">DevTools API</button>
        <button onclick="testNetworkRequests()">网络请求测试</button>
        <button onclick="testAdvancedFeatures()">高级功能</button>
        <button onclick="testErrorHandling()">错误处理</button>
        <button onclick="testPerformance()">性能监控</button>
        <button onclick="testMemoryUsage()">内存监控</button>
        <button onclick="testAsyncOperations()">异步操作</button>
        <button onclick="clearLogs()">清空日志</button>
        <button onclick="exportLogs()">导出日志</button>
        <button onclick="runAllTests()">运行所有测试</button>
        <button onclick="showStatus()">显示状态</button>
      </div>

      <div class="info">
        <h3>🔧 当前环境信息:</h3>
        <div class="code" id="env-info">加载中...</div>
      </div>

      <div class="info">
        <h3>📊 统计信息:</h3>
        <div class="code" id="stats-info">加载中...</div>
      </div>
    </div>

    <!-- 导入调试系统 -->
    <script type="module">
      // 导入调试系统
      import Debug from '../src/DebugLogger.js'

      // 配置调试系统
      Debug.updateConfig({
        serverUrl: `${window.location.protocol}//${window.location.hostname}:3000`,
        enableRemoteLogging: true,
        enableConsoleLogging: true,
        maxLocalLogs: 1000,
        autoSendInterval: 0,
      })

      // 使调试器全局可用
      window.Debug = Debug

      // 更新状态显示
      function updateStatus() {
        const status = Debug.getStatus()
        const statusEl = document.getElementById('connection-status')
        statusEl.textContent = status.isConnected ? '已连接 ✅' : '未连接 ❌'
        statusEl.style.color = status.isConnected ? 'green' : 'red'

        // 更新统计信息
        const statsEl = document.getElementById('stats-info')
        statsEl.textContent = JSON.stringify(status, null, 2)
      }

      // 定期更新状态
      setInterval(updateStatus, 2000)

      // 初始化
      updateStatus()

      // 显示环境信息
      const envInfo = {
        userAgent: navigator.userAgent,
        platform: navigator.platform,
        language: navigator.language,
        cookieEnabled: navigator.cookieEnabled,
        onLine: navigator.onLine,
        url: window.location.href,
        viewport: {
          width: window.innerWidth,
          height: window.innerHeight,
        },
        screen: {
          width: screen.width,
          height: screen.height,
          colorDepth: screen.colorDepth,
        },
      }

      document.getElementById('env-info').textContent = JSON.stringify(envInfo, null, 2)

      // 测试函数
      window.testBasicLogging = function () {
        Debug.group('基础日志测试')
        Debug.debug('这是调试信息', { timestamp: new Date() })
        Debug.info('这是信息日志', { level: 'info' })
        Debug.log('这是普通日志', '支持多个参数', { data: 'test' })
        Debug.warn('这是警告信息', { warning: true })
        Debug.error('这是错误信息', new Error('测试错误'))
        Debug.groupEnd()
      }

      window.testDevToolsAPI = function () {
        Debug.group('DevTools API测试')

        // 表格测试
        const testData = [
          { id: 1, name: 'Alice', score: 95 },
          { id: 2, name: 'Bob', score: 87 },
          { id: 3, name: 'Charlie', score: 92 },
        ]
        Debug.table(testData)

        // 计时测试
        Debug.time('计时测试')
        setTimeout(() => {
          Debug.timeLog('计时测试', '中间检查点')
          setTimeout(() => {
            Debug.timeEnd('计时测试')
          }, 500)
        }, 300)

        // 断言测试
        Debug.assert(true, '这个断言应该通过')
        Debug.assert(false, '这个断言应该失败')

        // 计数器测试
        Debug.count('测试计数器')
        Debug.count('测试计数器')
        Debug.count('其他计数器')

        // 调用栈测试
        Debug.trace('调用栈追踪测试')

        Debug.groupEnd()
      }

      window.testNetworkRequests = async function () {
        Debug.group('网络请求测试')

        // 手动记录请求
        const requestId = Debug.networkRequest('GET', '/api/test', {
          headers: { 'Accept': 'application/json' },
        })

        // 模拟响应
        setTimeout(() => {
          Debug.networkResponse(requestId, {
            status: 200,
            statusText: 'OK',
            headers: { 'Content-Type': 'application/json' },
            data: { message: '手动记录的请求响应' },
          })
        }, 500)

        // 实际fetch请求（会被自动拦截）
        try {
          const response = await fetch('https://jsonplaceholder.typicode.com/posts/1')
          const data = await response.json()
          Debug.info('Fetch请求成功', { url: response.url, status: response.status })
        } catch (error) {
          Debug.error('Fetch请求失败', error)
        }

        // 模拟失败的请求
        try {
          await fetch('https://nonexistent-domain-12345.com/api')
        } catch (error) {
          Debug.error('预期的网络错误', error.message)
        }

        Debug.groupEnd()
      }

      window.testAdvancedFeatures = function () {
        Debug.group('高级功能测试')

        // 对象检查
        const complexObj = {
          string: 'Hello World',
          number: 42,
          boolean: true,
          array: [1, 2, 3, { nested: 'value' }],
          object: {
            date: new Date(),
            func: () => 'test function',
            null: null,
            undefined: undefined,
          },
        }
        Debug.dir(complexObj)

        // 内存使用
        Debug.memory()

        // 性能标记
        Debug.mark('feature-test-start')

        // 模拟一些操作
        let result = 0
        for (let i = 0; i < 100000; i++) {
          result += Math.random()
        }

        Debug.mark('feature-test-end')
        Debug.measure('feature-test-duration', 'feature-test-start', 'feature-test-end')

        Debug.info('计算结果', { result: result.toFixed(2) })

        Debug.groupEnd()
      }

      window.testErrorHandling = function () {
        Debug.group('错误处理测试')

        // 同步错误
        try {
          throw new Error('模拟的同步错误')
        } catch (error) {
          Debug.error('捕获的同步错误', error)
        }

        // 异步错误
        Promise.reject(new Error('模拟的异步错误')).catch((error) => {
          Debug.error('捕获的异步错误', error)
        })

        // 类型错误
        try {
          null.someMethod()
        } catch (error) {
          Debug.error('类型错误', error)
        }

        Debug.groupEnd()
      }

      window.testPerformance = function () {
        Debug.group('性能监控测试')

        Debug.time('页面渲染模拟')
        Debug.time('数据处理')

        // 模拟数据处理
        const data = Array.from({ length: 10000 }, (_, i) => ({ id: i, value: Math.random() }))
        Debug.timeEnd('数据处理')

        Debug.time('DOM操作模拟')
        // 模拟DOM操作
        const div = document.createElement('div')
        div.innerHTML = `<p>测试元素 ${Date.now()}</p>`
        document.body.appendChild(div)

        setTimeout(() => {
          document.body.removeChild(div)
          Debug.timeEnd('DOM操作模拟')
          Debug.timeEnd('页面渲染模拟')
        }, 100)

        Debug.groupEnd()
      }

      window.testMemoryUsage = function () {
        Debug.group('内存监控测试')

        Debug.memory()

        // 创建一些对象来消耗内存
        const largeArray = new Array(100000).fill(0).map((_, i) => ({
          id: i,
          data: `item-${i}`,
          timestamp: Date.now(),
          random: Math.random(),
        }))

        Debug.info('创建了大型数组', { length: largeArray.length })
        Debug.memory()

        // 清理
        largeArray.length = 0

        setTimeout(() => {
          Debug.memory()
          Debug.info('内存测试完成')
          Debug.groupEnd()
        }, 1000)
      }

      window.testAsyncOperations = async function () {
        Debug.group('异步操作测试')

        Debug.time('异步操作总时间')

        // 并行异步操作
        const promises = [
          new Promise((resolve) => {
            Debug.time('异步任务1')
            setTimeout(() => {
              Debug.timeEnd('异步任务1')
              resolve('任务1完成')
            }, 300)
          }),
          new Promise((resolve) => {
            Debug.time('异步任务2')
            setTimeout(() => {
              Debug.timeEnd('异步任务2')
              resolve('任务2完成')
            }, 500)
          }),
          new Promise((resolve) => {
            Debug.time('异步任务3')
            setTimeout(() => {
              Debug.timeEnd('异步任务3')
              resolve('任务3完成')
            }, 200)
          }),
        ]

        const results = await Promise.all(promises)
        Debug.timeEnd('异步操作总时间')
        Debug.info('所有异步任务完成', { results })

        Debug.groupEnd()
      }

      window.clearLogs = function () {
        Debug.clear()
        Debug.info('日志已清空')
      }

      window.exportLogs = function () {
        const logs = Debug.getLogs()
        const networkLogs = Debug.getNetworkLogs()

        const exportData = {
          timestamp: new Date().toISOString(),
          logs,
          networkLogs,
          status: Debug.getStatus(),
        }

        const blob = new Blob([JSON.stringify(exportData, null, 2)], {
          type: 'application/json',
        })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `debug-logs-${Date.now()}.json`
        a.click()
        URL.revokeObjectURL(url)

        Debug.info('日志已导出', { logCount: logs.length, networkCount: networkLogs.length })
      }

      window.runAllTests = async function () {
        Debug.group('🚀 运行所有测试')
        Debug.info('开始运行所有测试...')

        testBasicLogging()
        await new Promise((resolve) => setTimeout(resolve, 500))

        testDevToolsAPI()
        await new Promise((resolve) => setTimeout(resolve, 1000))

        await testNetworkRequests()
        await new Promise((resolve) => setTimeout(resolve, 500))

        testAdvancedFeatures()
        await new Promise((resolve) => setTimeout(resolve, 500))

        testErrorHandling()
        await new Promise((resolve) => setTimeout(resolve, 500))

        testPerformance()
        await new Promise((resolve) => setTimeout(resolve, 1000))

        testMemoryUsage()
        await new Promise((resolve) => setTimeout(resolve, 2000))

        await testAsyncOperations()

        Debug.info('✅ 所有测试完成!')
        Debug.groupEnd()
      }

      window.showStatus = function () {
        const status = Debug.getStatus()
        const logs = Debug.getLogs()
        const networkLogs = Debug.getNetworkLogs()

        Debug.group('📊 系统状态信息')
        Debug.info('连接状态', status)
        Debug.info('日志统计', {
          totalLogs: logs.length,
          debugLogs: logs.filter((l) => l.level === 'debug').length,
          infoLogs: logs.filter((l) => l.level === 'info').length,
          warningLogs: logs.filter((l) => l.level === 'warn').length,
          errorLogs: logs.filter((l) => l.level === 'error').length,
        })
        Debug.info('网络请求统计', {
          totalRequests: networkLogs.length,
          successfulRequests: networkLogs.filter((r) => r.success).length,
          failedRequests: networkLogs.filter((r) => !r.success).length,
        })
        Debug.groupEnd()
      }

      // 页面加载完成后的初始化
      Debug.info('🌟 测试页面已加载', {
        url: window.location.href,
        timestamp: new Date().toISOString(),
        userAgent: navigator.userAgent,
      })
    </script>
  </body>
</html>


